<template>
  <van-button
    icon="star"
    type="default"
    v-if="is_collected"
    @click="quitCollections"
    :loading="isLoading"
    class="collected"
  />
  <van-button icon="star-o" type="default" v-else @click="goCollections" :loading="isLoading" />
</template>

<script>
// 导入收藏文章api和取消收藏文章api
import { isCollections, noCollections } from '@/assets/api/article'
// 导入vuex.state
import { mapState } from 'vuex'
export default {
  name: 'star',
  data() {
    return {
      isLoading: false
    }
  },
  props: {
    is_collected: {
      type: Boolean,
      required: true
    },
    aut_id: {
      type: [Number, Object, String],
      required: true
    }
  },
  methods: {
    async goCollections() {
      // 判断是否登入
      if (!this.user) {
        return this.$toast('请登入')
      }
      try {
        // 发起请求,加载状态开启
        this.isLoading = true
        var { data: res } = await isCollections(this.aut_id)
      } catch (err) {
        // 请求失败处理
        return this.$toast('收藏失败请稍后重试')
      }
      // 请求成功，更改收藏状态
      this.$emit('toCollect')
      // 关闭加载中
      this.isLoading = false
    },
    async quitCollections() {
      // 判断是否登入
      if (!this.user) {
        return this.$toast('请登入')
      }
      try {
        // 发起请求,加载状态开启
        this.isLoading = true
        var { data: res } = await noCollections(this.aut_id)
      } catch (err) {
        // 请求失败处理
        return this.$toast('取消收藏失败请稍后重试')
      }
      // 请求成功，更改收藏状态
      this.$emit('quitCollect')
      // 关闭加载中
      this.isLoading = false
    }
  },
  computed: {
    ...mapState(['user'])
  }
}
</script>

<style lang="less" scoped>
.collected {
  .van-icon {
    color: #ffa000;
  }
}
</style>
